﻿using System.IO;
using System.Text.Json;

namespace JIG_SoftTemplate.Common.Services
{
    public class JsonConfigService
    {
        private const string ConfigFileName = "AppSettings.json";

        private readonly LoggerService loggerService;

        public JsonConfigService(LoggerService loggerService)
        {
            this.loggerService = loggerService;
        }

        public async Task<T> LoadConfigAsync<T>(T defaultValue = default) where T : new()
        {
            try
            {
                var filePath = GetConfigFilePath();
                if (!File.Exists(filePath))
                {
                    loggerService.Info("配置文件不存在，返回默认值");
                    await SaveConfigAsync(defaultValue ?? new T());
                    return defaultValue ?? new T();
                }

                await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                return await JsonSerializer.DeserializeAsync<T>(fs) ?? new T();
            }
            catch (Exception ex)
            {
                loggerService.Error("加载配置文件失败", ex);
                return defaultValue ?? new T();
            }
        }

        public async Task SaveConfigAsync<T>(T config)
        {
            try
            {
                var filePath = GetConfigFilePath();
                var dirPath = Path.GetDirectoryName(filePath);

                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                await using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                await JsonSerializer.SerializeAsync(fs, config, options);
                loggerService.Info("配置文件保存成功");
            }
            catch (Exception ex)
            {
                loggerService.Error("保存配置文件失败", ex);
                throw;
            }
        }

        private static string GetConfigFilePath()
        {
            // 使用程序根目录存储配置文件
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFileName);
        }
    }
}
